<template>
  <div>
    <el-form ref="ruleForm" :model="form" :rules="rules" label-width="150px">
      <el-form-item label="账号:" prop="username">
        <el-input
          v-model="form.username"
          placeholder="账号"
          width="100px"
        ></el-input>
      </el-form-item>
      <el-form-item label="员工姓名:" prop="name">
        <el-input v-model="form.name" placeholder="员工姓名"></el-input>
      </el-form-item>
      <el-form-item label="手机号:">
        <el-input v-model="form.phone" placeholder="手机号"></el-input>
      </el-form-item>
      <el-form-item label="性别：" prop="sex">
        <el-radio v-model="form.sex" label="1">男</el-radio>
        <el-radio v-model="form.sex" label="2">女</el-radio>
      </el-form-item>
      <el-form-item label="身份证号：">
        <el-input v-model="form.idNumber" placeholder="身份证号"></el-input>
      </el-form-item>
      <el-row>
        <el-button @click="$router.go(-1)">取消</el-button>
        <el-button type="warning" @click="handleSave">保存</el-button>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { addEmployee, getEmployeeById, editEmployee } from "@/api/employee";
export default {
  data() {
    return {
      form: {
        name: "",
        phone: "",
        sex: "1",
        idNumber: "",
        username: "",
      },
      rules: {
        username: [{ required: true, message: "请输入账号", trigger: "blur" }],
        name: [{ required: true, message: "请输入账号", trigger: "blur" }],
        sex: [{ required: true, message: "请选择", trigger: "change" }],
      },
    };
  },
  created() {
    if (this.isEdit) {
      getEmployeeById(this.$route.query.id).then((res) => {
        this.form = res.data;
      });
    }
  },
  methods: {
    handleSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            editEmployee(this.form).then((res) => {
              this.$message.success("编辑成功");
              this.$router.go(-1);
            });
          } else {
            addEmployee(this.form).then((res) => {
              this.$message.success("新增成功");
              this.$router.go(-1);
            });
          }
        } else {
          return false;
        }
      });
    },
  },

  computed: {
    isEdit() {
      this.$route.meta.title =
        this.$route.query.isEdit === "1" ? "编辑员工" : "添加员工";
      return this.$route.query.isEdit === "1" ? true : false;
    },
  },
};
</script>
